<?php

/**
 * HistoryTable
 *
 * @author Administrator
 * @version
 */

require_once 'Zend/Debug.php';

class Default_Model_DbTable_HistoryTable extends Zend_Db_Table_Abstract {
	
	/**
	 * The default table name
	 */
	protected $_name = 'dict_history';


	/**
	 *
	 * @param int $user_id
	 * @param int $count
	 * @return Zend_Db_Statement_Interface
	 */
	public function top($user_id, $count) {
		// XXX: I have not idea about why if I used ? instend of $count variable in sql expresion will cause exception
		$sql = "select user_id, word, count(word) as count, max(create_date) as created  FROM dict_history where user_id = ? group by word  order by created desc limit " . $count;
		return $this->getAdapter()->query($sql, $user_id);
	}

	/**
	 *
	 * @param int $user_id
	 * @param int $count
	 * @return Zend_Db_Statement_Interface
	 */
	public function history($user_id, $count) {
		$sql = "select user_id, word, max(create_date) as created, sum(favorited) > 0 as favorited FROM dict_history where user_id = ? group by word  order by created desc limit " . $count;
		return $this->getAdapter()->query($sql, $user_id);
	}
	
	public function isFavorited($user_id, $word) {
		$sql =  "select count(favorited) from dict_history where user_id = ? and word = ? and favorited= 1";
		/* @var $stmt = Zend_Db_Statement_Interface*/
		$stmt =  $this->getAdapter()->query($sql, array($user_id, $word));
		return $stmt->fetchColumn(0) != 0;
	}
	
	public function markFavorite($user_id, $word, $marked) {
		$sql ="UPDATE dict_history SET favorited=?  WHERE user_id=? and  word=?";
		$stmt =  $this->getAdapter()->query($sql, array($marked, $user_id, $word));
	}
	 
}
